package com.shxc.smarttrade.old.push;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.main.MainActivity;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.old.utils.CloseAllActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";

    //接受消息
    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        initNotifiManager();
        try {
            Bundle bundle = intent.getExtras();
            Loger.e(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                //注册id （该方法下不需要调用其他方法）
                Loger.e(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                Loger.e(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
//                {"content":"这个是测试消息","status":"0","title":"这个是标题","extra":"这个是ext"}
                analysis(bundle.getString(JPushInterface.EXTRA_EXTRA));

            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                Loger.e(TAG, "[MyReceiver] 接收到推送下来的通知" + JPushInterface.EXTRA_MESSAGE);
//                int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
//                Loger.e(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Loger.e(TAG, "[MyReceiver] 用户点击打开了通知");
                //该方法下接收非自定义消息，用于跳转
                Loger.e("message",bundle.getString(JPushInterface.EXTRA_EXTRA));
                String json = bundle.getString(JPushInterface.EXTRA_EXTRA);
                ExtraMessageModel model = gson.fromJson(json, ExtraMessageModel.class);
                if (model!=null) {
                    switch (model.getStatus()){
                        case 0:
                            Intent intents = new Intent(mContext, MainActivity.class);
                            intents.putExtra("status", status);
                            intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intents);
                            break;
                        case 1:
                            MyApplication.getInstance().getMainActivity().jump(status);
                            break;
                        case 2:
                            CloseAllActivity.getScreenManager().clearEcxeptMainActivity();
                            EventBus.getDefault().post(new EventDatas(EventContents.DIALOG_PUSH_SEND_MSG, status));
                            break;
                    }
                }

            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                Loger.e(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Loger.e(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                Loger.e(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {

        }

    }

    private void analysis(String string) {
        Loger.e("json", string);
        PushModel model = gson.fromJson(string, PushModel.class);
        showNotification(model.getTitle(), model.getContent(), model.getStatus(), model.getExtra());
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Loger.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Loger.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    private NotificationManager mManager;
    private Notification.Builder mNotification;

    Gson gson = new Gson();
    Context mContext;
    int status = 0;

    // 初始化通知栏配置
    private void initNotifiManager() {
        // 获得通知管理器
        mManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        int icon = R.mipmap.ic_launcher2;
        mNotification = new Notification.Builder(mContext);
        mNotification.setContentTitle("标题");
        mNotification.setTicker("内容");
        mNotification.setLargeIcon(BitmapFactory.decodeResource(
                mContext.getResources(), icon));
        mNotification.setSmallIcon(icon);
        mNotification.setDefaults(Notification.DEFAULT_SOUND);// 默认声音
        mNotification.setAutoCancel(true);
    }

    // 弹出Notification
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void showNotification(String title, String content, int status, String extra) {
        Intent i = new Intent();
        i.setClass(mContext, DialogPushActivity.class);
        i.putExtra("title", title);
        i.putExtra("content", content);
        i.putExtra("status", status);
        i.putExtra("extra", extra);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, (int) Math.random(), i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mNotification.setContentText(content);
        mNotification.setContentTitle(title);
        Intent intent = new Intent(Intent.ACTION_MAIN);
        mNotification.setContentIntent(pendingIntent);
        mNotification.setDeleteIntent(PendingIntent.getBroadcast(mContext, (int) Math.random(), intent, 0));
        Notification notification = mNotification.build();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        mManager.notify((int) Math.random(), notification);
    }

    class ExtraMessageModel{

        /**
         * status : 0
         * id : 0
         */

        private int status;
        private int id;

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }
}
